import React, { useState, useEffect } from "react";
import Module from './components/module';
import dayjs from 'dayjs';
import { Button, View, Form } from '@tarojs/components'
import { toast, loginData, goBack } from '@/utils/utils';
import Taro, { useDidShow, useDidHide } from '@tarojs/taro';
import { fetchInformationCollectionDetail, fakeSaveUserInformation } from '@/server/shop'
import { getCurrentInstance } from '@tarojs/taro'
import Router from '@/utils/router';
import { Mask } from '@/components/UiComponents'
import './index.scss';
const CollectWps = (props) => {
  const { params } = getCurrentInstance().router

  const { id, goodsId } = params
  const account = loginData() || {}
  const { username, unionId, openId, organizationId, profile, token, paramKey, shareId, shareType } = account
  const [data, setData] = useState({})
  const [model, setModel] = useState(false)
  const [showHideListId, setShowHideListId] = useState([])
  const [list, setList] = useState([]);
  const fetchInitData = (list) => {
    let showList = []
    list.forEach((item, index) => {
      const { type, option = [], value = '' } = item
      if (type === 'Radio' || type === 'CheckBox' || type === 'DropDown') {
        option.forEach(val => {
          const { associationList = [] } = val
          if (associationList.length > 0) {
            showList = [...showList, ...associationList]
          }
        })
      }
    })
    let hideList = Array.from(new Set(showList));
    list.forEach((item) => {
      const { type, option = [], value = '' } = item
      if (type === 'Radio' || type === 'CheckBox' || type === 'DropDown') {
        option.forEach(val => {
          const { associationList = [], label } = val
          if (associationList.length > 0) {
            if (value.includes(label)) {
              hideList = hideList.filter((o, j) => {
                let flag = associationList.reduce((values, vals) => {
                  if (vals === o) {
                    return false
                  }
                  return values
                }, true)
                return flag
              })
            }
          }
        })
      }
    })
    setShowHideListId(hideList)
  }
  const fetchInformationCollectionDetails = () => {
    fetchInformationCollectionDetail({ id, organizationId }).then(val => {
      const { informationCollection } = val
      if (!token) {
        Taro.showModal({
          title: '提示',
          content: '请登录后填写表单',
          success: () => {
            Router('login')
          }
        })
      }
      setData(informationCollection)
    })
  }

  useEffect(() => {
    fetchInformationCollectionDetails()
  }, [])
  useEffect(() => {
    fetchInitData(list)
  }, [list])
  useEffect(() => {
    const { content } = data
    if (content) {
      setList(JSON.parse(content))
    }


  }, [data])
  const fakeSaveUserInformationInfo = (data = {}) => {
    if (!token) {
      return Router('login')
    }
    else {
      const showList = list.filter((val, index) => {
        return showHideListId.reduce((vals, indexs) => {
          if (indexs === index) {
            return false
          }
          return vals
        }, true)
      })
      const updateFlag = showList.reduce((item, val, index) => {
        const { type } = val
        if (type === 'Cephalogram' || type === 'ParagraphDescription' || item.flag === false) {
          return item
        }
        else if (val.require && !val.value) {
          return {
            flag: false,
            message: "请填写第" + (index + 1) + '题'
          }
        }
        else {
          if (type === 'Input' && item.flag) {
            const {
              font_rule,
              font_length,
              value,
              rule } = val
            if (rule || font_rule) {
              if (rule === 'number' && !/^\d+$/.test(Number(value))) {
                return {
                  flag: false,
                  message: '请填写数字'
                }
              }
              else if (rule === 'mobile' & ! /^1[3-9]\d{9}$/.test(value)) {
                return {
                  flag: false,
                  message: '请填写正确的手机号'
                }
              }
              else if (rule === 'idCard' && !/^[1-9]\d{5}(18|19|20|21|22)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/.test(value)) {
                return {
                  flag: false,
                  message: '请填写正确的身份证号'
                }

              }
              else if (rule === 'bankCard' && !/^(?:13[0-9]|14[57]|15[0-3]|16[6]|17[6-8]|18[0-9]|19[8-9])[0-9]{8}$/.test(value)) {
                return {
                  flag: false,
                  message: '请填写正确的银行卡号'
                }
              }
              else if (rule === 'email' && !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(value)) {
                return {
                  flag: false,
                  message: '请填写正确的邮箱'
                }
              } else if (font_rule === 'more' && value.length < font_length) {
                return {
                  flag: false,
                  message: '文字不能少于' + font_length
                }
              } else if (font_rule === 'under' && value.length > font_length) {
                return {
                  flag: false,
                  message: '文字不能超过' + font_length
                }
              }
              else {
                return item
              }

            }
          }
          return item
        }
      }, {
        flag: true, message: null
      })
      if (!updateFlag.flag) {
        return toast(updateFlag.message)
      } else {
        fakeSaveUserInformation({
          paramKey,
          informationCollectionId: id,
          id: id,
          organizationId,
          unionId,
          goodsId,
          answer: JSON.stringify(showList),
          shareId,
          shareType,
        }).then(e => {
          toast('问卷填写成功')
          goBack();
        })
      }
    }

  }
  const ChangeValue = ({ value = {}, index }) => {
    setList(list.map((val, o) => {
      if (o === index) {
        return {
          ...val,
          ...value
        }
      }
      return val
    }))
  }

  const showFlag = (index) => {
    return showHideListId.reduce((vals, indexs) => {
      if (indexs === index) {
        return false
      }
      return vals
    }, true)
  }
  return (
    <View className="CollectWps_box">
      {list.map((item, index) => {
        const { type } = item
        const RenderContent = Module[type]
        if (!RenderContent || !showFlag(index)) {
          return null
        }
        return <RenderContent ChangeValue={ChangeValue} data={item} index={index} key={index}></RenderContent>
      })}
      <View style={{ textAlign: "center", paddingBottom: Taro.pxTransform(24) }}>
        {list.reduce((item, val) => {
          const { type, disabled } = val
          if (type === 'Cephalogram') {
            return !disabled
          }
          return item
        }, true) && <Button style={{ width: '60%' }} onClick={() => fakeSaveUserInformationInfo()} color='primary'>提交</Button>}
      </View>
      {/* <Modal
        visible={model}
        content='请登录后填写表单'
        closeOnAction
        onClose={() => {
          setModel(false)
        }}
        actions={[
          {
            key: 'confirm',
            text: '去登陆',
            onClick: (e) => {
              history.push({
                pathname: '/live/login'
              })
            }
          },
        ]}
      /> */}
    </View>
  );
}
export default CollectWps